<?php

namespace Index\Controller;

use Think\Controller;
use Index\ViewModel;
use Index\Service;

/**
 * 说明：系统管理控制器
 * 作者：王楠
 * 创建日期：2017-09-12
 */
class SystemController extends CommonController {

    /**
     * 项目列表
     */
    public function applist() {
	$state_enum = getenumbykey('app_state');
	$state_arr = getarrbyenum($state_enum);
	$state = trim(I('ddlstate'));
	$show = I('hidshow', '1');
	$begintime = trim(I('txtbegintime'));
	$endtime = trim(I('txtendtime'));
	$keyword = trim(I('txtkeyword'));
	$listclass = 'btn-white';
	$smallclass = 'btn-white';
	$bigclass = 'btn-white';
	switch ($show) {
	    case '1':
		$listclass = 'btn-primary';
		break;
	    case '2':
		$smallclass = 'btn-primary';
		break;
	    case '3':
		$bigclass = 'btn-primary';
		break;
	    default:
		$listclass = 'btn-primary';
		break;
	}

	$map['app_state'] = array('neq', '3');
	if (!empty($state)) {
	    $map['app_state'] = $state;
	}
	if (!empty($begintime) || !empty($endtime)) {
	    if (!empty($begintime) && !empty($endtime)) {
		$map['ctime'] = array('between', array(strtotime($begintime), strtotime($endtime) + 60));
	    } else if (!empty($begintime)) {
		$map['ctime'] = array('between', array(strtotime($begintime), time() + 60));
	    } else if (!empty($endtime)) {
		$map['ctime'] = array('between', array(0, strtotime($endtime) + 60));
	    }
	}
	if (!empty($keyword)) {
	    $where['id'] = array('eq', $keyword);
	    $where['app_flag'] = array('like', '%' . $keyword . '%');
	    $where['app_name'] = array('like', '%' . $keyword . '%');
	    $where['_logic'] = 'or';
	    $map['_complex'] = $where;
	}
	$model = M('chat_systemset');
	$total = $model->where($map)->count();
	$row = '10';
	$page = new Service\PageService($total, $row);
	$fpage = $page->fpage();
	$field = array(
	    'id', 'app_flag', 'app_logo', 'app_name', 'app_state', 'ctime'
	);
	$order = 'ctime desc, id desc';
	$data = $model->where($map)->limit($page->listfirst, $page->listRows)->field($field)->order($order)->select();
	foreach ($data as $key => $value) {
	    $data[$key]['state_lab'] = $data[$key]['app_state'] == '1' ? '下架' : '上架';
	    $data[$key]['state_class'] = $data[$key]['app_state'] == '1' ? 'btn-danger' : 'btn-info';
	    $data[$key]['app_state_text'] = $state_enum[$data[$key]['app_state']];
	    $data[$key]['ctime'] = date('Y-m-d H:i', $data[$key]['ctime']);
	}
	$search = array('statesel' => $state, 'keyword' => $keyword, 'begintime' => $begintime, 'endtime' => $endtime);
	$btnshowclass = array('list' => $listclass, 'small' => $smallclass, 'big' => $bigclass);
	$this->assign(array(
	    'data' => $data,
	    'fpage' => $fpage,
	    'total' => $total,
	    'search' => $search,
	    'statearr' => $state_arr,
	    'show' => $show,
	    'btnshowclass' => $btnshowclass,
	));
	$this->display();
    }

    /**
     * 项目添加
     */
    public function appadd() {
	$id = I('id');
	$btnname = '添加';
	$columnname = '添加项目';
	$state_enum = getenumbykey('app_state');
	$state_arr = getarrbyenum($state_enum);
	if (!empty($id)) {
	    $columnname = '修改项目';
	    $btnname = '修改';
	    $model = M('chat_systemset');
	    $data = $model->where(array('id' => $id))->find();
	    $logo = $data['app_logo'];
	    $name = $data['app_name'];
	    $code = $data['app_flag'];
	    $state = $data['app_state'];
	    $ctime = date('Y-m-d H:i', $data['ctime']);
	}
	foreach ($state_arr as $key => $value) {
	    if ($state == $value['value']) {
		$state_arr[$key]['selected'] = "selected='selected'";
	    }
	}
	$this->assign(array(
	    'id' => $id,
	    'logo' => $logo,
	    'name' => $name,
	    'code' => $code,
	    'state' => $state,
	    'ctime' => $ctime,
	));
	$this->assign('columnname', $columnname);
	$this->assign('btnname', $btnname);
	$this->assign('statearr', $state_arr);
	$this->display();
    }

    /**
     * 项目添加提交
     * @return type
     */
    public function appaddsubmit() {
	if (!IS_POST) {
	    $this->error('非法访问！');
	}
	$id = I('id');
	$logo = trim(I('logo'));
	$name = trim(I('name'));
	$code = trim(I('code'));
	$state = trim(I('state'));
	if (empty($logo)) {
	    $response = array('ret' => '1002', 'code' => '图片不能为空！');
	    return $this->ajaxReturn($response, 'json');
	}
	if (empty($name)) {
	    $response = array('ret' => '1002', 'code' => '名称不能为空！');
	    return $this->ajaxReturn($response, 'json');
	}
	if (empty($code)) {
	    $response = array('ret' => '1002', 'code' => '标识不能为空！');
	    return $this->ajaxReturn($response, 'json');
	}
	if (empty($state)) {
	    $state = '1';
	}
	$data = array(
	    'ratio' => '100',
	    'user_logo' => '',
	    'img_default' => '',
	    'invite_word' => '终于等到你啦，快来一起玩耍吧！',
	    'init_gold' => '100',
	    'invite_gold' => '300',
	    'message_gold' => '10',
	    'video_gold' => '300',
	    'user_img_switch' => '1',
	    'video_switch' => '2',
	    'qq_login_switch' => '1',
	    'weixin_login_switch' => '1',
	);
	$data['app_logo'] = $logo;
	$data['app_name'] = $name;
	$data['app_flag'] = $code;
	$data['app_state'] = $state;
	if (empty($id)) {
	    $data['ctime'] = time();
	}
	$model = M('chat_systemset');
	if (!empty($id)) {
	    if ($model->where(array('id' => $id))->save($data)) {
		$response = array('ret' => '1001', 'code' => '修改成功！');
	    } else {
		$response = array('ret' => '1001', 'code' => '修改成功！');
	    }
	} else {
	    if ($model->where(array('app_state' => array('neq', '3'), 'app_flag' => $code))->count()) {
		$response = array('ret' => '1002', 'code' => '该项目已存在！');
		return $this->ajaxReturn($response, 'json');
	    }
        $this->logtxtsystem($data,'chat_systemset',$id);
	    if ($model->add($data)) {
		$map = array();
		$map['state'] = array('neq', '3');
		$map['username'] = $code;
		$model = M('chat_admin');
		if ($model->where($map)->count()) {
		    $model->where($map)->save(array('state' => '1'));
		    $response = array('ret' => '1001', 'code' => '添加成功！');
		    return $this->ajaxReturn($response, 'json');
		}
		$data = array();
		$data['username'] = $code;
		$data['password'] = md5('123456');
		$data['state'] = $state;
		$data['ctime'] = time();
		$data['app_flag'] = $code;
		$this->logtxtsystem($data,'chat_admin');
		$model->add($data);
		$response = array('ret' => '1001', 'code' => '添加成功！');
	    } else {
		$response = array('ret' => '1002', 'code' => '添加失败！');
	    }
	}
	return $this->ajaxReturn($response, 'json');
    }

    /**
     * 系统设置
     */
    public function index() {
	$switch_enum = getenumbykey('switch');
	$update_enum = getenumbykey('appupdate_type');
	$imgs_id_switch_arr = getarrbyenum($switch_enum);
	$video_switch_arr = getarrbyenum($switch_enum);
	$qq_switch_arr = getarrbyenum($switch_enum);
	$wx_switch_arr = getarrbyenum($switch_enum);
	$android_app_update_arr = getarrbyenum($update_enum);
	$ios_app_update_arr = $android_app_update_arr;
	$id = I('id');
	if (!empty($id)) {
	    $map['id'] = $id;
	}
	$model = M('chat_systemset');
	$data = $model->where($map)->order('id desc')->find();
	if ($data != null) {
	    $id = $data['id'];
	    $ratio = $data['ratio'];
	    $user_logo = $data['user_logo'];
	    $img_default = $data['img_default'];
	    $invite_word = $data['invite_word'];
	    $init_gold = (int) $data['init_gold'];
	    $invite_gold = (int) $data['invite_gold'];
	    $message_gold = (int) $data['message_gold'];
	    $video_gold = (int) $data['video_gold'];
	    $free_cumulative = (int) $data['free_cumulative'];
	    $imgs_id_switch = (int) $data['user_img_switch'];
	    $video_switch = (int) $data['video_switch'];
	    $qq_login_switch = $data['qq_login_switch'];
	    $weixin_login_switch = $data['weixin_login_switch'];
	    $message_config = $data['message_config'];
	    $agora_config = $data['agora_config'];
	    $version = $data['version'];
	    $share_ratio = $data['share_ratio'];
	    if (!empty($message_config)) {
		$message_config = json_decode($message_config, true);
		$account_sid = $message_config['accountSid'];
		$account_token = $message_config['accountToken'];
		$app_id = $message_config['appId'];
	    }
	    if (!empty($agora_config)) {
		$agora_config = json_decode($agora_config, true);
		$app_certificate = $agora_config['appCertificate'];
		$app_id = $agora_config['appId'];
	    }
	    $android_version = $data['version_android'];
	    if (!empty($android_version)) {
		$version_android = json_decode($android_version, true);
		$android_switch = $version_android['switch'];
	    }
	    $ios_version = $data['version_ios'];

	    if (!empty($ios_version)) {
		$version_ios = json_decode($ios_version, true);
		$ios_switch = $version_ios['switch'];
	    }
	}
	foreach ($imgs_id_switch_arr as $key => $value) {
	    if ($value['value'] == $imgs_id_switch) {
		$imgs_id_switch_arr[$key]['switch_selected'] = "selected='selected'";
	    }
	}
	foreach ($video_switch_arr as $key => $value) {
	    if ($value['value'] == $video_switch) {
		$video_switch_arr[$key]['switch_selected'] = "selected='selected'";
	    }
	}
	foreach ($qq_switch_arr as $key => $value) {
	    if ($value['value'] == $qq_login_switch) {
		$qq_switch_arr[$key]['switch_selected'] = "selected='selected'";
	    }
	}
	foreach ($wx_switch_arr as $key => $value) {
	    if ($value['value'] == $weixin_login_switch) {
		$wx_switch_arr[$key]['switch_selected'] = "selected='selected'";
	    }
	}
	foreach ($android_app_update_arr as $key => $value) {
	    if ($value['value'] == $android_switch) {
		$android_app_update_arr[$key]['switch_selected'] = "selected='selected'";
	    }
	}
	foreach ($ios_app_update_arr as $key => $value) {
	    if ($value['value'] == $ios_switch) {
		$ios_app_update_arr[$key]['switch_selected'] = "selected='selected'";
	    }
	}

	$this->assign(array(
	    'id' => $id,
	    'ratio' => $ratio,
	    'user_logo' => $user_logo,
	    'img_default' => $img_default,
	    'invite_word' => $invite_word,
	    'init_gold' => $init_gold,
	    'invite_gold' => $invite_gold,
	    'message_gold' => $message_gold,
	    'video_gold' => $video_gold,
	    'free_cumulative' => $free_cumulative,
	    'video_switch' => $video_switch,
	    'qq_login_switch' => $qq_login_switch,
	    'weixin_login_switch' => $weixin_login_switch,
	    'message_config' => $message_config,
	    'agora_config' => $agora_config,
	    'version' => $version,
	    'imgsidswitcharr' => $imgs_id_switch_arr,
	    'videoswitcharr' => $video_switch_arr,
	    'qqswitcharr' => $qq_switch_arr,
	    'wxswitcharr' => $wx_switch_arr,
	    'android_app_update_arr' => $android_app_update_arr,
	    'ios_app_update_arr' => $ios_app_update_arr,
	    'android_version' => $version_android,
	    'ios_version' => $version_ios,
        'share_ratio'=>$share_ratio,
	));
	$this->display();
    }

    /**
     * 系统设置提交
     * @return type
     */
    public function systemsubmit() {
	$id = I('id');
	$ratio = trim(I('ratio'));
	$user_logo = trim(I('userlogo'));
	$img_default = trim(I('imgdefault'));
	$invite_word = trim(I('inviteword'));
	$init_gold = trim(I('initgold'));
	$invite_gold = trim(I('invitegold'));
	$message_gold = trim(I('messagegold'));
	$video_gold = trim(I('videogold'));
	$free_cumulative = trim(I('freecumulative'));
	$imgs_id_switch = trim(I('imgsidswitch'));
	$video_switch = trim(I('videoswitch'));
	$qq_switch = trim(I('qqswitch'));
	$wx_switch = trim(I('wxswitch'));
	$accountsid_msg = trim(I('accountsid_msg'));
	$accounttoken_msg = trim(I('accounttoken_msg'));
	$appid_msg = trim(I('appid_msg'));
	$modelid_msg = trim(I('modelid_msg'));
	$appcertificate_agora = trim(I('appcertificate_agora'));
	$appid_agora = trim(I('appid_agora'));
	$version = trim(I('version'));
	$share_ratio = trim(I('share_ratio'));
	$message_config = array(
	    'accountSid' => $accountsid_msg,
	    'accountToken' => $accounttoken_msg,
	    'appId' => $appid_msg,
	    'modelId' => $modelid_msg
	);
	$message_config = json_encode($message_config);
	$agora_config = array(
	    'appCertificate' => $appcertificate_agora,
	    'appId' => $appid_agora
	);
	$agora_config = json_encode($agora_config);


	$ddliosswitch = trim(I('ddliosswitch'));
	$ios_version = trim(I('ios_version'));
	$ios_url = trim(I('ios_url'));
	$version_ios = array(
	    'switch' => $ddliosswitch,
	    'version' => $ios_version,
	    'url' => $ios_url
	);
	$version_ios = json_encode($version_ios);


	$ddlandroidswitch = trim(I('ddlandroidswitch'));
	$android_version = trim(I('android_version'));
	$android_url = trim(I('android_url'));
	$version_android = array(
	    'switch' => $ddlandroidswitch,
	    'version' => $android_version,
	    'url' => $android_url
	);
	$version_android = json_encode($version_android);

	$data = array(
	    'ratio' => (int) $ratio,
	    'user_logo' => $user_logo,
	    'img_default' => $img_default,
	    'invite_word' => $invite_word,
	    'init_gold' => (int) $init_gold,
	    'invite_gold' => (int) $invite_gold,
	    'message_gold' => (int) $message_gold,
	    'video_gold' => (int) $video_gold,
	    'free_cumulative' => (int) $free_cumulative,
	    'user_img_switch' => $imgs_id_switch,
	    'video_switch' => $video_switch,
	    'qq_login_switch' => $qq_switch,
	    'weixin_login_switch' => $wx_switch,
	    'message_config' => $message_config,
	    'agora_config' => $agora_config,
	    'version_android' => $version_android,
	    'version_ios' => $version_ios,
	    'share_ratio' => (int)$share_ratio,
	    'utime' => time(),
	);
	if (empty($id)) {
	    $data['ctime'] = time();
	}
	$this->logtxtsystem($data,'chat_systemset',$id);
	$model = M('chat_systemset');
	if (!empty($id)) {
	    if ($model->where(array('id' => $id))->save($data)) {
		$response = array('ret' => '1001', 'code' => '修改成功！');
	    } else {
		$response = array('ret' => '1001', 'code' => '修改成功！');
	    }
	} else {
	    if ($model->add($data)) {
		$response = array('ret' => '1001', 'code' => '添加成功！');
	    } else {
		$response = array('ret' => '1002', 'code' => '添加失败！');
	    }
	}
	return $this->ajaxReturn($response, 'json');
    }

    /**
     * 上架/下架提交
     * @return type
     */
    public function flagsubmit() {
	$id = I('id');
	if (!empty($id)) {
	    $model = M('chat_systemset');
	    $data = $model->where(array('id' => $id))->find();
	    if (!empty($data)) {
		$state = $data['app_state'];
		$lab = $state == '1' ? '下架' : '上架';
		$state = $state == '1' ? '2' : '1';
		$data['app_state'] = $state;
		$result = $model->save($data);
		if ($result) {
		    $model = M('chat_admin');
		    $model->where(array('app_flag' => $data['app_flag']))->save(array('state' => $state));
		    return $this->ajaxReturn(array('ret' => '1001', 'code' => $lab . '成功！', 'data' => $state));
		} else {
		    return $this->ajaxReturn(array('ret' => '1002', 'code' => $lab . '失败！', 'data' => $state));
		}
	    } else {
		return $this->ajaxReturn(array('ret' => '1002', 'code' => '对不起，该项目可能已被删除！'));
	    }
	}
    }

    /**
     * 删除提交
     * @return type
     */
    public function deletesubmit() {
	$id = I('id');
	if (!empty($id)) {
//	    $model = M('chat_systemset');
//	    $result = $model->where(array('id' => $id))->delete();
//	    if ($result) {
//		return $this->ajaxReturn(array('ret' => '1001', 'code' => '删除成功！'));
//	    } else {
//		return $this->ajaxReturn(array('ret' => '1002', 'code' => '删除失败！'));
//	    }

	    $model = M('chat_systemset');
	    $data = $model->where(array('id' => $id))->find();
	    if (!empty($data)) {
		$state = '3';
		$data['app_state'] = $state;
		$result = $model->save($data);
		if ($result) {
		    $model = M('chat_admin');
		    $model->where(array('app_flag' => $data['app_flag']))->save(array('state' => $state));
		    return $this->ajaxReturn(array('ret' => '1001', 'code' => '删除成功！', 'data' => $state));
		} else {
		    return $this->ajaxReturn(array('ret' => '1002', 'code' => '删除失败！', 'data' => $state));
		}
	    } else {
		return $this->ajaxReturn(array('ret' => '1002', 'code' => '对不起，该项目可能已被删除！'));
	    }
	}
    }

    //上传图片
    public function imgupload() {
	$config = [
	    'maxSize' => 1048576, // 设置附件上传大小
	    'exts' => ['jpg', 'gif', 'png', 'jpeg'], // 设置附件上传类型
	    'rootPath' => './Uploads/', // 设置附件上传根目录
	    'savePath' => '', // 设置附件上传（子）目录
	    'autoSub' => false,
	    'subName' => '',
	    'saveName' => array('uniqid', ''),
	];
	$rootPath = $config['rootPath'];
	if (!is_dir($rootPath)) {
	    mkdir($rootPath);
	}
	$upload = new \Think\Upload($config); // 实例化上传类
	// 上传单个文件
	$info = $upload->upload();
	if (!$info) {// 上传错误提示错误信息
	    $error = $upload->getError();
	    $data['ret'] = '1002';
	    $data['code'] = $error;
	    echo json_encode($data);
	} else {// 上传成功 获取上传文件信息
	    $access_key_id = C('ACCESS_KEY_ID');
	    $access_key_secret = C('ACCESS_KEY_SECRET');
	    $img_url = C('IMG_URL');
	    $img_url2 = C('IMG_URL2');
	    $picName = $info['logoimg']['savename'];
	    $picSize = $info['logoimg']['size'];
	    $picTmp = $info['logoimg']['tmp_name'];
	    $success = new \Vendor\OSS\OssClient($access_key_id, $access_key_secret, $img_url2);
	    $ext = explode('.', $picName)[1];
	    $picRemoteName = 'pc_' . time() . rand(100000, 999999) . '.' . $ext;
	    $bucket = C('BUCKET');
	    $object = $picRemoteName;
	    $filePath = $rootPath . $picName;
	    try {
		$success->uploadFile($bucket, $object, $filePath);
		unlink($rootPath . $picName);
		$img = $img_url . '/' . $object;
		$data['ret'] = '1001';
		$data['code'] = '上传成功！';
		$data['data'] = $img;
		echo json_encode($data);
	    } catch (OssException $e) {
		$response = array('ret' => '1002', 'code' => '远程上传错误！');
		echo json_encode($data);
	    }

//	    //返回本地路径
//	    $img = C('LOCALHOST_URL') . '/Uploads/' . $info['logoimg']['savename'];
//	    $data['ret'] = '1001';
//	    $data['code'] = '上传成功！';
//	    $data['data'] = $img;
//	    echo json_encode($data);
	}
    }

    public function integral(){
        $data = M('chat_vip')->order('vip asc')->select();
        if($_POST){
//            var_dump(I('txt'));
//            var_dump(I('txtfreecumulative1'));
//            var_dump($numArr);
//            dump(count($data));
            

        }
        $this->assign('data',$data);
        $this->display();
    }
    public function integraladd(){
        $txt = (string)I('txt');
            $num = json_decode(str_replace('&quot;', '"', $txt), true);
            $data = M('chat_vip')->order('vip asc')->select();
            $num=array_filter($num);
            if(count($num)==count($data)) {
                foreach ($num as $key=>$value){
                    $shu = $key+1;
                    M('chat_vip')->where('vip = '.$shu)->setField('integral',$value);
                }
//

                $response = array('ret' => '1001', 'code' => '更新成功');
            }else{
                $response = array('ret' => '1002', 'code' => '更新失败');
            }
            return $this->ajaxReturn($response, 'json');
    }
}
